package com.ruoyi.search.runner;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.search.client.CmsClient;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

//@Component
public class SearchRunner implements ApplicationRunner {

    @Autowired
    private CmsClient cmsClient;

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("项目启动,执行全量同步....");
        List<Map> list = cmsClient.list();

        //对ES做添加
        IndexRequest indexRequest = new IndexRequest("2112a","goods");

        for(Map data: list){
            indexRequest.id(String.valueOf(data.get("id")));

            Map sourceMap = new HashMap();
            sourceMap.put("name",data.get("title"));
            sourceMap.put("category",data.get("category"));
            sourceMap.put("brand",data.get("brand"));
            sourceMap.put("price",data.get("price"));

            String spec = (String) data.get("spec");
            Map specMap = JSONObject.parseObject(spec,Map.class);

            sourceMap.put("spec",specMap);
            sourceMap.put("url",data.get("image"));

            String create_time = (String) data.get("create_time");
            create_time = create_time.replace("T", " ");

            sourceMap.put("createTime",create_time);
            indexRequest.source(sourceMap);
            restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        }

    }

}
